/*******************************************************************************
 * Copyright (c) 2018.
 * This file was written by Fancyears·Milos·Malvis @connor. Any question/bug you can't post to 1243093366@qq.com.
 * ALL RIGHTS RESERVED.
 ******************************************************************************/
package org.fancyears.main;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class ProgressBarExample1 {
	private Text text;
	private ProgressBar progressBar;
	private int max;
	private int i;
	private int Value;
	private int value;

	public void ProgessBarExample1() throws InterruptedException {
		final Display display = Display.getDefault();
		final Shell shell = new Shell(SWT.MIN | SWT.CLOSE);
		shell.setText("正在下載");
		shell.setSize(315, 127);
		shell.setLocation(350, 180);
		shell.setLayout(new FormLayout());

		progressBar = new ProgressBar(shell, SWT.HORIZONTAL);

		FormData data = new FormData(237, 20);
		data.top = new FormAttachment(100, -65);
		data.bottom = new FormAttachment(100, -48);
		data.right = new FormAttachment(100, -67);
		data.left = new FormAttachment(100, -272);
		progressBar.setLayoutData(data);

		max = progressBar.getMaximum();

		text = new Text(shell, SWT.BORDER);
		text.setEnabled(false);

		final FormData fd_text = new FormData();
		fd_text.right = new FormAttachment(0, 280);
		fd_text.top = new FormAttachment(progressBar, 0, SWT.TOP);
		fd_text.left = new FormAttachment(progressBar, 5, SWT.RIGHT);
		text.setLayoutData(fd_text);

		new Thread() {
			public void run() {
				for (i = 1; i < max; i++) {
					System.out.println(i);
					try {
						Thread.sleep(100);
					} catch (Throwable e) {

					}
					display.asyncExec(new Runnable() {
						public void run() {
							progressBar.setSelection(i);
							Value = progressBar.getMaximum();
							value = progressBar.getSelection();
							System.out.println("value:" + value);
							text.setText(value + "%");

							if (Value == value) {
								final Display dis = Display.getDefault();
								Shell sh = new Shell(dis);
								MessageDialog md = new MessageDialog(sh, "信息提示", null, "下载完成", 2, new String[] { "确定" },
										0);
								md.open();
								shell.dispose();
								return;
							}
						}
					});
				}
			}
		}.start();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
	}

	public static void main(String args[]) throws InterruptedException {
		ProgressBarExample1 pe = new ProgressBarExample1();
		pe.ProgessBarExample1();
	}
}
